<script setup lang="ts">
import { apiUploadPost } from "@/tool/request";
import { AxiosProgressEvent } from "axios";
import { UploaderFileListItem } from "vant";
import { onMounted, ref, watch } from "vue";
const props = defineProps<{
  url: string;
  multiple?: boolean;
}>();
const fileList = ref<
  {
    url: string;
    file?: File;
    message: string;
    objectUrl: string;
    status: string;
  }[]
>([]);
const progress = ref(0);
const afterRead = (file: UploaderFileListItem) => {
  if (file.file) {
    apiUploadPost(file.file, (_progress: AxiosProgressEvent) => {
      console.log(_progress.progress);
      if (_progress.progress) {
        progress.value = _progress.progress * 100;
      }
    }).then((res) => {
      // console.log(res.data,fileList.value);
      fileList.value[fileList.value.length - 1].url = res.data;
      emit("success", res.data);
    });
  }
};

const emit = defineEmits<{
  (e: "success", _url: string): void;
}>();

onMounted(() => {
  if (props.url?.length > 0) {
    fileList.value = [{ url: props.url, message: "", objectUrl: "", status: "" }];
  }else{
    fileList.value.length = 0;
  }
});

watch(
  () => props.url,
  () => {
    if (props.url?.length > 0) {
      fileList.value = [{ url: props.url, message: "", objectUrl: "", status: "" }];
    }else{
      fileList.value.length = 0;
    }
  }
);
</script>

<template>
  <div class="upload_com">
    <van-uploader
      style="grid-area: a"
      v-model="fileList"
      multiple
      :after-read="afterRead"
      accept="image/*"
    />
    <van-progress
      v-model="progress"
      v-if="progress != 0 && progress != 100"
    ></van-progress>
  </div>
</template>

<style lang="scss" scope>
.upload_com {
}
</style>
